<?php
declare (strict_types = 1);

namespace app\command;

use app\server\RedisClientSever;
use app\server\SendNotice;
use app\server\SendRequestServer;
use app\server\WeChatServer;
use GuzzleHttp\Psr7\Request;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use Workerman\RedisQueue\Client;;
use Workerman\Timer;
use Workerman\Worker;

class Vin extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('convert')
            ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
            ->addOption('mode', 'm', Option::VALUE_OPTIONAL, 'Run the workerman server in daemon mode.')
            ->setDescription('the workerman command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('convert start');

        $action = $input->getArgument('action');
        $mode = $input->getOption('mode');


        // 重新构造命令行参数,以便兼容workerman的命令
        global $argv;

        $argv = [];

        array_unshift($argv, 'think', $action);
        if ($mode == 'd') {
            $argv[] = '-d';
        } else if ($mode == 'g') {
            $argv[] = '-g';
        }

        // 在这里放心的实例化worker,
        // 就像参照workerman文档写一样,
        // 无非在workerman的文档里,代码是新建纯php文件,但在这里,写到了一个方法里.
        $task = new Worker();
// 开启多少个进程运行定时任务，注意业务是否在多进程有并发问题
        $task->count = 1;
        $task->onWorkerStart = function(Worker $task)
        {
//            $body = '{"f6-data-backendSESSIONID": "ca5c656c-ab69-4698-828f-a9e79330a30d","un": "11861816161253482584","sensorsdata2015jssdkcross":"%7B%22distinct_id%22%3A%2218c7274105d9e6-0029ede13ce465fa-7e433c49-1930176-18c7274105e1e50%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22%24device_id%22%3A%2218c7274105d9e6-0029ede13ce465fa-7e433c49-1930176-18c7274105e1e50%22%7D"}';
//
//
//            $guzzleClient = new \GuzzleHttp\Client();
//            $rab = new Request('POST', 'http://49.232.137.209:8000/api/vin?vin=LE4WG4CB4HL280603', [], $body);
//            var_dump($guzzleClient->send($rab)->getBody()->getContents());

            // 有用
            $client = new Client('redis://47.97.123.68:6379', [
                'auth' => 'hjzhjz459'
            ]);

            // 消息订阅
            $client->subscribe('user-1', function($data) use ($client){

                try {
                    (new SendNotice())->sendMes($data);
                } catch (\Exception $e) {
                    // 发送企业微信机器人，报告错误
                    $app = WeChatServer::getInstance()->server();
                    $app->group_robot_messenger->message('程序发送错误，错误原因：' . $e->getMessage() . $e->getFile(). $e->getLine())->toGroup('0fd3ca80-5547-419b-a4a5-e323924127e1')->send();
                    var_dump($e->getMessage());

                    // 重新入队
                    if ($e->getCode() === 1000100) {
                        $client->send('user-1', $data);
                    }
                }
                var_export('success' . "\n");

            });

            // 每5秒执行一次
            $time_interval = 3;
            Timer::add($time_interval, function() use ($client)
            {
                $currentIndex = Cache::get('current-index') ?? 710;

                $res = Db::name('message_wwd6c3e7b79a384bed')
                    ->whereIn('roomid', [
                        'wry5rPBwAAuorcePqmmWGxCm9G-yy_Qw', 'wry5rPBwAAP3rb7b-ZSkwOoOZl4qldrQ', 'wry5rPBwAATDLp5B8Ys7TOFwxoS4qvTA',
                        'wry5rPBwAANHPPvw-31vR2fN-hr2EyRg', 'wry5rPBwAAZ-JWQ7EKqrEhI0TgzhUCFw', 'wry5rPBwAAUGciwc3cqcc-JkoR2WyzdQ',
                        'wry5rPBwAA2U2LneMRDF3rkjQ6i_B6DQ', 'wry5rPBwAACZeWkF9oTGX2yGixBa3SNA', 'wry5rPBwAAYMArkGwftoX6A6AvGt8GbA',
                        'wry5rPBwAADllWpWwJpTqG5TKKptA_aQ', 'wry5rPBwAAHs1ds0pj7k5J25alLN5OqA', 'wry5rPBwAAwO1hC2w7qqNALDh6BQtfAg',
                        'wry5rPBwAAICrULXuFS_1NEbsiq1X1Xw', 'wry5rPBwAA-o_hFJC17JBqOremRxkU5w', 'wry5rPBwAAFoJ9gfe5eYMH4-nZhS4JRA',
                        'wry5rPBwAAHr1oI-YtMNLo7mA_3_dFrQ', 'wry5rPBwAAYyRxnCdoxk_aBZLJU8XXlw', 'wry5rPBwAA56wu8zyheMrl9d-IM70l2A',
                        'wry5rPBwAALS-DoV639nELvmlGAMbwdg', 'wry5rPBwAAaXQGGOOUHfEM1KRn6O4hzA', 'wry5rPBwAAQfl8nm8ny693v0WqXK6T7Q',
                        'wry5rPBwAA1RmSYn3e9IFwpxW-rK-56A', 'wry5rPBwAAmYul7MBzXwqiB7yum8ZgbA', 'wry5rPBwAAtgEhHgaNgAWlz0v2IYlACA',
                        'wry5rPBwAAJHWEiaSfswjuAvPmS_S1Qw', 'wry5rPBwAAM6wgtwUH6h7UnOvtxduSCQ', 'wry5rPBwAANHvaNtLApF-51-OSc5t_uQ',
                        'wry5rPBwAAhJYUFKJz1BREjITqsDaIyg', 'wry5rPBwAAUj5oBx5080dBo0-81J3pYQ', 'wry5rPBwAAf2rOnh0q_0Rnh49Lbintdg',
                        'wry5rPBwAAHCHF-B5awORHaZeJar868Q', 'wry5rPBwAAl3MNdDddZmgl_SBlYETvSg', 'wry5rPBwAAz_KQwQWjTnNE4ZbdmQCReg',
                        'wry5rPBwAApDySmdqctuj-6GVWER-laQ', 'wry5rPBwAAgNw_0wWitErfpP2LCeKc9g', 'wry5rPBwAAERKzDgRJgvnx3syLrF49pg',
                        'wry5rPBwAAscLMXtFJ_5VYF089-Uin-A', 'wry5rPBwAA-yiS4TWOYFuUeP2AmI9FpA', 'wry5rPBwAAqg82tt6DlY5o3pgyYH7a9Q',
                        'wry5rPBwAAszeegrlERHFNb7r4tWeu0Q', 'wry5rPBwAAEFCqC6g2kQLq8YZAevRPuw', 'wry5rPBwAAGoCGHW96VxD0s747_o8I8A',
                        'wry5rPBwAAFCfGALie72DTwTF8h1STHg', 'wry5rPBwAADUrO8VpEw6Sr3U_V6V6FfA', 'wry5rPBwAAmjvV60jjAD3K_py3RdBxng',
                        'wry5rPBwAAGsKXBSOo6wtAPiT7GYeiqA', 'wry5rPBwAAi_59CzNopK0CrF1PmAPkMw', 'wry5rPBwAAR4inQj5cHXd0QVpIhN5c6A',
                        'wry5rPBwAAL13xAQEkUz3l0fNTAb1_Yg', 'wry5rPBwAAMOBCcTNGbAlQLkJ4JhxJ4g', 'wry5rPBwAAb4zpUXD-hkDfQCLyKH1sfw',
                        'wry5rPBwAAte6Nex11rLyLaN6tddNcOA', 'wry5rPBwAAm2muUFGoM3MBgkiB_9KTLg', 'wry5rPBwAAIekWVLsti8Odx0kLE2isAg',
                        'wry5rPBwAAXMvl4QEubv_anEwOul03KQ', 'wry5rPBwAAjzS5VCu8VxRFaCBZF4B2lA', 'wry5rPBwAA65uMXnSXLteVnTn41FRO9w',
                        'wry5rPBwAAAWQ7vXFb8cmSJml_mChejg', 'wry5rPBwAAPuFMtRdFFC5n7zT66x6ZHA', 'wry5rPBwAALDluEqy2DZo6eJpPgK6Ncw',
                        'wry5rPBwAAjGVYGmqo-yYsJ3C5N2yX7w', 'wry5rPBwAAT6eQQ9JYbjG0RLh0cAVgug', 'wry5rPBwAARrBXu5zZ99bwtEhApPbUdA',
                        'wry5rPBwAAPe4H5G2iaP5CjFX0Y8yFdw', 'wry5rPBwAA7eut0sU63WIs2RGBW8C9Ig', 'wry5rPBwAAFbLfS8o9tgoscYU12Xlhcg',
                        'wry5rPBwAAOi0ZDLsRZBqji5BYdB4UDw', 'wry5rPBwAA2obV5ZTjGjffzEsfjjR-SA', 'wry5rPBwAAN64fyE41RcPB4KAlczglmQ'
                    ])
                    ->where('status', '<>', 5)
                    ->where('id', '>', $currentIndex)
                    ->field('id, msgfrom, media_path, roomid, msgtype, text')
                    ->find();

                if ($res !== null) {
                    // 防止重复执行
                    Cache::set('current-index', $res['id']);

                    Db::name('message_wwd6c3e7b79a384bed')->where('id', $res['id'])->update([
                        'status' => 5
                    ]);

                    // 写入到队列工具中，等待处理
                    $client->send('user-1', $res);
                }

            });
        };

        // 进程2 - 检查可用cookie值
//        $listenWork = new Worker();
//        $listenWork->count = 1;
//        $listenWork->onWorkerStart = function(Worker $t) {
//            $redis = RedisClientSever::getInstance()->redisClientServer();
//            $app = WeChatServer::getInstance()->server();
//
//            Timer::add(3600, function () use ($redis, $app) {
//
//                $r = $redis->SRANDMEMBER('cookies_cache');
//
//                try {
//                    if ($r === null) {
//                        throw new Exception('获取可用cookie数据失败，请补充');
//                    }
//
////                    $cookie = json_decode($r, true);
////                    if (!is_array($cookie) || count($cookie) != 5) {
////                        throw new Exception('获取可用cookie数据结构错误，请检查1');
////                    }
////
////                    $count = $redis->SCARD('cookies_cache');
////                    if ($count <= 1) {
////                        throw new Exception("可用cookie不足，请及时补充，剩余{$count}");
////                    }
//
//                    // 心跳维持
//                    $active = false;
//                    $searchTime = $redis->get('vin_search_time');
//                    if (!$searchTime) {
//                        // 时间戳比较
//                        $diff = time() - $searchTime;
//                        if ($diff >= 5400) {
//                            // 模拟数据发送
//                            $active = true;
//                        }
//                    } else {
//                        $active = true;
//                    }
//
//                    // 心跳维持
//                    if ($active) {
//                        (new SendRequestServer())->send('LVSHCFDB4HE337751', [
//                            'module_id' => 14,
//                            'key' => '蓄电池',
//                            'data_type' => '常规保养'
//                        ]);
//                    }
//
//                    $app->group_robot_messenger->message('cookie异常：心跳维持')->toGroup('0fd3ca80-5547-419b-a4a5-e323924127e1')->send();
//                } catch (\Exception $e) {
//                    $app->group_robot_messenger->message('cookie异常：' . $e->getMessage())->toGroup('0fd3ca80-5547-419b-a4a5-e323924127e1')->send();
//                }
//
//            });
//
//            echo 'check-success' . PHP_EOL;
//
//        };

// 运行worker
        Worker::runAll();
    }
}
